package com.xypw.util;




import com.et.ar.ActiveRecordBase;
import com.et.ar.exception.ActiveRecordException;
import com.et.ar.exception.TransactionException;
import com.xypw.models.ProjectManageInfo;

public class ProCodeUtil {
	
	public static synchronized Integer getMaxId(String areaCode,String year) throws ActiveRecordException{
		
		String[] params = new String[] { areaCode, year };
		
		//查询ID
		Integer maxProId = getId(params);
		int start = 10000;
		//ID是否存在
		if (maxProId == null) {
			//ID不存在则创建ID
			creatId(new Object[]{areaCode, year , start});
		} else {
			//ID存在则更新
			start = maxProId.intValue() + 1;
			int i = updateId(new Object[]{areaCode, year , maxProId});
			//如果没有更新到记录，则说明ID已经被使用并更新了
			//需要使用行级锁，锁定后查询，更新
			if(i < 1){
					try {
						
						//开始事务
						ActiveRecordBase.beginTransaction();
						//增加行级锁
						ActiveRecordBase.findBySql(ProjectManageInfo.class, "select 'x' from tb_orgProCode where orgCode=? and proyear=? for update",params);
						//重新查询
						maxProId = getId(params);
						//ID增加
						start = maxProId.intValue() + 1;
						//更新ID
						updateId(new Object[]{areaCode, year , maxProId});
						//提交
						ActiveRecordBase.commit();
					} catch (TransactionException e) {
						e.printStackTrace();
						//回滚
						ActiveRecordBase.rollback();
						throw e;
					}
				}
			}
		
		return start;
	}
	
	public static Integer getId(Object[] params) throws ActiveRecordException{
		return (Integer) ActiveRecordBase.executeScalar(
				"select maxProId from tb_orgProCode where orgCode=? and proyear=?",
				params);
	}
	
	public static int updateId(Object[] params) throws ActiveRecordException {
		return ActiveRecordBase.execute(
				"update tb_orgProCode set maxProId=maxProId+1 where orgCode=? and proyear=? and maxProId=?",
				params);
	}
	
	public static int creatId(Object[] params) throws ActiveRecordException{
		return 	ActiveRecordBase.execute(
				"insert into tb_orgProCode(orgCode, proyear, maxProId) values(?,?,?)", params);
	}
	
}
